package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.domain.po.Teacher;
import com.campus.service.TeacherService;
import com.campus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/add")
    public R addTeacher(@RequestBody Teacher teacher) {
        Teacher savedTeacher = teacherService.saveTeacher(teacher);
        return R.success(savedTeacher);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/delete/{id}")
    public R deleteTeacher(@PathVariable Integer id) {
        boolean removed = teacherService.deleteTeacherById(id);
        return removed ? R.success(200) : R.error(500, "Failed to delete teacher");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/update")
    public R updateTeacher(@RequestBody Teacher teacher) {
        Teacher updatedTeacher = teacherService.updateTeacher(teacher);
        return updatedTeacher != null ? R.success(updatedTeacher) : R.error(500, "Failed to update teacher");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public R getTeacher(@PathVariable Integer id) {
        Teacher teacher = teacherService.getTeacherById(id);
        return teacher != null ? R.success(teacher) : R.error(500, "Teacher not found");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list")
    public R getTeacherList(
            @RequestParam(required = false) String teacherName,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        if (teacherName != null && !teacherName.isEmpty()) {
            wrapper.like("teacher_name", teacherName); // 模糊查询教师名称
        }
        return R.success(teacherService.page(new    Page<>(page, size), wrapper).getRecords());
    }
}
